import { BadRequestException, Injectable } from '@nestjs/common';
import { FindOptionsWhere, Like, Repository } from 'typeorm';
import { MenuManage } from './entities/menuManage.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateMenuDto } from './dto/create.dto';
import { UpdateMenuDto } from './dto/update.dto';
import { ListDto } from './dto/list.dto';
import { DeleteMenuDto } from './dto/delete.dto';

@Injectable()
export class MenuManageService {
  @InjectRepository(MenuManage)
  private readonly MenuManageRepository: Repository<MenuManage>;

  async createMenu(menu: CreateMenuDto) {
    const isExist = await this.MenuManageRepository.findOne({
      where: { parent_id: menu.parent_id, name: menu.name, path: menu.path },
    });
    if (isExist) {
      return new BadRequestException('菜单已存在');
    }
    return await this.MenuManageRepository.save(menu);
  }

  async deleteMenu(deleteMenuDto: DeleteMenuDto) {
    const menu = await this.MenuManageRepository.findOne({
      where: { id: deleteMenuDto.id },
    });

    if (!menu) {
      return new BadRequestException('菜单不存在');
    }

    return await this.MenuManageRepository.delete(deleteMenuDto.id);
  }

  async updateMenu(menu: UpdateMenuDto) {
    const oldMenu = await this.MenuManageRepository.findOne({
      where: { id: menu.id },
    });
    if (!oldMenu) {
      return new BadRequestException('菜单不存在');
    }
    return await this.MenuManageRepository.update(menu.id, menu);
  }

  async getDetail(params: Partial<MenuManage>) {
    return await this.MenuManageRepository.find({ where: params });
  }

  async getMenuList(listDto: ListDto) {
    const { page, limit, name, parent_id, ...resetListDto } = listDto;
    const query: FindOptionsWhere<Omit<ListDto, 'page' | 'limit'>> =
      resetListDto;
    if (name) {
      query.name = Like(`%${name}%`);
    }
    if (parent_id) {
      query.parent_id = parent_id;
    }
    const [list, total] = await this.MenuManageRepository.findAndCount({
      where: query,
      skip: (page - 1) * limit,
      take: limit,
    });
    return {
      list,
      total,
      page,
      limit,
    };
  }
  async getMenuTree() {
    return await this.MenuManageRepository.find();
  }
}
